import PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from datetime import datetime    
import time,json
from helpFunc import *
dd = dam()
import os
class myLine(QLineEdit):
    def __init__(self):
        super().__init__()
    def wheelEvent(self, e):
        aa = e.angleDelta().y()/120
        t = window.numIn.text()
        try:
            t = int(t)+int(aa)
        except:
            t = 0
        if t>59:
            t -= 60
        if t<0:
            t+=60
        window.numIn.setText(str(t))
        
def LastNlines(fname, N): 
    size = os.path.getsize(fname)
    lines = [] 
    with open(fname,encoding='utf8') as f: 
        si = size-1024*100      
        if si<0:
            si=0
        while True:
            try:
                si += 1
                f.seek(si)                 
                lines = list(f)
            except:
                continue
            break
    return lines[-N:] 

def getFile():
    st = LastNlines('chi.log',80)
    ss = ''
    for one in st:
        try:
            ss+='\n\n'
            one = one.split()
            si = '[%s %s]'%(one[1],one[2])
            tt = len(one[3])
            for k in range(0,len(one[3]),400):
                ss+=si+one[3][k:k+400]
        except:
            print('ex',one)
    return ss

class win(QWidget):
    def __init__(self):
        super().__init__()
        self.co = 0
        self.fre = 1
        l = QVBoxLayout()
        hl = QHBoxLayout()
        self.tii = le= QLabel()
        hl.addWidget(le)       
        self.lBtn = b =  QPushButton('<')
        b.clicked.connect(self.l)
        b.setFixedWidth(30)
        hl.addWidget(b)
        self.freL = le= QLabel(str(self.fre))
        hl.addWidget(le)              
        self.rBtn = b =  QPushButton('>')
        b.clicked.connect(self.r)
        b.setFixedWidth(30)
        hl.addWidget(b)
        self.pauseBtn = b = QPushButton('pause')
        b.clicked.connect(self.cli)
        hl.addWidget(b)
        self.bomBtn = b = QPushButton('unbottom')
        b.clicked.connect(self.keepBom)
        hl.addWidget(b)        
        self.numIn = le= myLine()
        le.setFixedWidth(60)     
        hl.addWidget(le)
        self.showBtn = b = QPushButton('show')
        b.clicked.connect(self.sh)
        hl.addWidget(b)           
        self.numOut = la = QLabel()
        hl.addWidget(la)
        self.code = le = QLineEdit()
        hl.addWidget(le)
        l.addLayout(hl)
        self.t = t= QTextEdit()
        t.selectionChanged.connect(self.cha)
        l.addWidget(t)
        self.setLayout(l)
        self.timer = ti = QTimer()
        ti.timeout.connect(self.ti)
        ti.start(1000)
        self.pause = False
        self.keepB = True
        
    def l(self):
        if self.fre==1:
            return
        self.fre-=1
        self.freL.setText(str(self.fre))
        
    def r(self):
        self.fre+=1
        self.freL.setText(str(self.fre))
        
    def sh(self):
        self.showBtn.setDisabled(True)
        n = 0
        try:
            n = int(self.numIn.text())
        except:
            pass
        now = datetime.now()     
        cur = int(now.strftime("%S"))
        di = 0
        if n<cur:
            di = cur-n
        else:
            di = cur+60-n
        n = di-1
        print (n)                
        from ctr import getText
        lenM,pp = getText( n)
        self.numOut.setText(str(lenM))
        self.pause = True
        self.pauseBtn.setText('play')
        t=self.t
        if not pp:
            self.showBtn.setDisabled(False)            
            return
        t.setText(pp)
        cursor = t.textCursor()
        t.selectAll()
        bf = t.textCursor().blockFormat()
        bf.setLineHeight(10, QTextBlockFormat.LineDistanceHeight) 
        t.textCursor().setBlockFormat(bf)                      
        t.setFontPointSize(15)
        t.setTextCursor( cursor )           
        self.showBtn.setDisabled(False)
                
    def keepBom(self):
        self.keepB = not self.keepB
        if self.keepB:
            self.bomBtn.setText('unbottom')
        else:
            self.bomBtn.setText('bottom')
    
    def cli(self):
        self.pause = not self.pause
        
        if self.pause:
            self.pauseBtn.setText('play')
        else:
            self.pauseBtn.setText('pause')
            
    def ti(self):
        self.co+=1
        now = datetime.now()        
        self.tii.setText(now.strftime("%H:%M:%S"))
        if  self.pause:
            return
        if self.co%self.fre != 0:
            return
        t = self.t
        oriPos = -t.cursorRect().top()    
        s = getFile()              
        t.setText(s)
        cursor = t.textCursor()
        t.selectAll()
        bf = t.textCursor().blockFormat()
        bf.setLineHeight(10, QTextBlockFormat.LineDistanceHeight) 
        t.textCursor().setBlockFormat(bf)                      
        t.setFontPointSize(15)
        t.setTextCursor( cursor )   
        t.verticalScrollBar().setValue(oriPos);
        if self.keepB:
            QTimer.singleShot(0, self.toBottom)
        
    def toBottom(self):
        t = self.t
        t.verticalScrollBar().setValue(t.verticalScrollBar().maximum());
        
    def cha(self):
        if not self.pause:
            return
        cursor = self.t.textCursor()
        st = self.t.toPlainText()[int(cursor.selectionStart()):int(cursor.selectionEnd())]
        st = st[:30]
        ss = ''
        for i in st:
            if len(ss)>50:
                break
            if i in dd.m2:
                ss += i+str(oct(dd.m2[i])[2:])+" "
        self.code.setText(ss)
        f = self.code.font()
        f.setPointSize(14) # sets the size to 27
        self.code.setFont(f)            

app = QApplication([])
window = win()
window.show()
app.exec_()